package com.movies.service.controller.admin;

import cn.dev33.satoken.annotation.SaCheckLogin;
import cn.dev33.satoken.annotation.SaCheckRole;
import cn.dev33.satoken.stp.SaTokenInfo;
import cn.dev33.satoken.stp.StpUtil;
import cn.hutool.crypto.SecureUtil;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.movies.service.common.Constants;
import com.movies.service.common.Result;
import com.movies.service.entity.Admin;
import com.movies.service.service.AdminService;
import io.swagger.v3.oas.annotations.Operation;
import lombok.Data;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;


@RestController
@RequestMapping("/admin")
public class AdminLoginController {

    @Autowired
    private AdminService adminService;

//    管理员登录
    @PostMapping("/login")
    public Result login(@RequestBody LoginReq req) {
        if (req.getAname() == null || req.getPassword() == null) {
            return Result.error(Constants.CODE_500, "请输入用户名和密码");
        }
        Admin admin = adminService.getOne(new LambdaQueryWrapper<Admin>().eq(Admin::getAname, req.getAname()));
        if (admin == null) {
            return Result.error(Constants.CODE_500, "用户名或密码错误，请重试");
        }
        if (admin.getStatus() != null && admin.getStatus() == 0) {
            return Result.error(Constants.CODE_400, "账号已禁用");
        }
        BCryptPasswordEncoder encoder = new BCryptPasswordEncoder();
        String stored = admin.getPassword();
        String raw = req.getPassword();
        boolean matched;
        if (stored != null && stored.startsWith("$2")) {
            matched = encoder.matches(raw, stored);
        } else {
            String pwdMd5 = SecureUtil.md5(raw);
            matched = pwdMd5.equalsIgnoreCase(stored);
        }
        if (!matched) {
            return Result.error(Constants.CODE_500, "用户名或密码错误，请重试");
        }
        // 旧密码为 MD5 时，登录成功后自动迁移为 BCrypt
        if (stored == null || !stored.startsWith("$2")) {
            admin.setPassword(encoder.encode(raw));
            adminService.updateById(admin);
        }
        // 登录并设置会话信息
        StpUtil.login(admin.getId());
        StpUtil.getSession().set("admin", admin);
        SaTokenInfo tokenInfo = StpUtil.getTokenInfo();
        return Result.success("登录成功", tokenInfo);
    }

//    获取当前登录的管理员信息
    @GetMapping("/profile")
    @SaCheckLogin
    @SaCheckRole("ADMIN")
    public Result profile() {
        Object loginId = StpUtil.getLoginIdDefaultNull();
        if (loginId == null) {
            return Result.error(Constants.CODE_401, "未登录");
        }
        Admin admin = (Admin) StpUtil.getSession().get("admin");
        return Result.success("已登录", admin);
    }

//    注销当前登录
    @PostMapping("/logout")
    @SaCheckLogin
    public Result logout() {
        StpUtil.logout();
        return Result.success("已注销");
    }

//    登录请求体
    @Data
    public static class LoginReq {
        private String aname;
        private String password;
    }
}
